/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fresher.utility;

import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author quangtm5
 */
public class ConnectionPool {
    
    private static ConnectionPool connectionPoolInstance = null;
    
    private ArrayList<ConnectionObject> connectionList;
    
    //blocking queue
    //private BlockingQueue<ConnectionObject> connectionQueue = new  LinkedBlockingQueue<>();
    
    private String databaseName = "cafe";
    private String userName = "root";
    private String passWord = "root";
    private int initialConnectionCount = 10;
    
    private ConnectionPool()
    {
        connectionList = new ArrayList<>();
        //create DatabaseUtility object and push into connectionList
        for(int i = 0 ; i < this.initialConnectionCount ; i++)
        {
            ConnectionObject connectObject = new ConnectionObject(this.userName, this.passWord, this.databaseName);
                                   
            this.connectionList.add(connectObject);

        }
        
    }
    
    /**
     * Create an instance of ConnectionPool
     * 
     * @return ConnectionPool instance with all constructed attributes
     */
    public static synchronized ConnectionPool getConnectionPool()
    {
        if (connectionPoolInstance == null)
        {
            connectionPoolInstance = new ConnectionPool();
        }
        
        return connectionPoolInstance;
    }
    
    
    public ConnectionObject getFreeConnectionObject()
    {
        int amountOfConnection = connectionList.size();
        for(int i = 0; i < amountOfConnection ; i++)
        {
            if(connectionList.get(i).isFree())
            {
               
                //if there is a free connection in connectionList
                ConnectionObject freeConnectionObject = connectionList.get(i);

                //set busy now
                freeConnectionObject.setBusy();

                System.out.println("Connection Pool - connectionList size : " + connectionList.size());
                
                return freeConnectionObject;
          
            }
        }
        
        //all are busy now
        //create a new connection and add to connectionList
        ConnectionObject newConnectionObject = new ConnectionObject(this.userName, this.passWord, this.databaseName);
        this.connectionList.add(newConnectionObject);
        
        
        
        return newConnectionObject;
    }
    
    
}
